package com.example.seed.aop;

import com.example.seed.annotations.AutoLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class LogAspect {

    private final LogPoint logPoint;

    public LogAspect(LogPoint logPoint) {
        this.logPoint = logPoint;
    }

    @Pointcut("@annotation(com.example.seed.annotations.AutoLog)")
    public void pointcut() {
    }

    /**
     * 保存系统操作日志
     *
     * @param joinPoint 连接点
     * @return 方法执行结果
     * @throws Throwable 调用出错
     */
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        long beginTime = System.currentTimeMillis();

        //解析Log注解
        String methodName = joinPoint.getSignature().getName();
        Method method = currentMethod(joinPoint, methodName);
        AutoLog log = method.getAnnotation(AutoLog.class);
        //日志入库
        if (log != null) {
            logPoint.add(joinPoint, methodName, log.value());
        }
        //方法执行
        //Object proceed = joinPoint.proceed();
        //long endTime = System.currentTimeMillis();
        return joinPoint.proceed();
    }

    /**
     * 获取当前执行的方法
     *
     * @param joinPoint  连接点
     * @param methodName 方法名称
     * @return 方法
     */
    private Method currentMethod(ProceedingJoinPoint joinPoint, String methodName) {

        //获取目标类的所有方法，找到当前要执行的方法
        Method[] methods = joinPoint.getTarget().getClass().getMethods();
        Method resultMethod = null;
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                resultMethod = method;
                break;
            }
        }
        return resultMethod;
    }
}
